package cn.fff.system.service.impl;

import cn.fff.model.system.SysUser;
import cn.fff.model.vo.RouterVo;
import cn.fff.model.vo.SysUserQueryVo;
import cn.fff.system.mapper.SysUserMapper;
import cn.fff.system.service.SysMenuService;
import cn.fff.system.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public IPage<SysUser> list(Long current, Long limit, SysUserQueryVo sysUserQueryVo) {
        IPage<SysUser> page = new Page<>(current, limit);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        String kw = sysUserQueryVo.getKeyword();
        if (StringUtils.isNotBlank(kw)) {
            wrapper.or(w -> w.like(SysUser::getUsername, kw)
                    .or().like(SysUser::getName, kw)
                    .or().like(SysUser::getPhone, kw)
            );
        }
        wrapper.orderByDesc(SysUser::getId);
        this.page(page, wrapper);
        return page;
    }

    @Override
    public boolean updateStatusById(String id, Integer status) {
        SysUser sysUser = new SysUser();
        sysUser.setStatus(status);
        sysUser.setId(id);
        return this.updateById(sysUser);
    }

    @Override
    public SysUser getUserInfoByUserName(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        return getOne(wrapper);
    }

    @Override
    public Map<String, Object> getUserInfoById(String id) {
        Map<String, Object> map = new HashMap<>();
        // 根据 id 查询用户信息
        SysUser sysUser = this.getById(id);
        // 根据 id 查询菜单权限值
        List<RouterVo> routerVos = sysMenuService.getUserMenuListByUserId(id);
        List<String> buttons = sysMenuService.getUserButtonList(id);

        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("username", sysUser.getUsername());
        map.put("name", sysUser.getName());
        map.put("introduction", sysUser.getDescription());
        map.put("roles", "[\"admin\"]");
        // 菜单权限数据
        map.put("routes", routerVos);
        // 按钮权限数据
        map.put("buttons", buttons);

        return map;
    }
}
